package com.store.app.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.store.app.ExitApplication;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.EventBusBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.ToastUtils;
import com.store.app.zxing.Capture_ZxingActivity;

import org.json.JSONObject;

import java.lang.ref.WeakReference;

import de.greenrobot.event.EventBus;

/**
 * 激活亲情卡
 */
public class ActiveFamilyActivity extends Capture_ZxingActivity implements IOnHttpListener {

    private View retreat;
    private static String cardNo;//卡号
    private RelativeLayout ryScanResult;
    private TextView tvCardCode;
    private TextView tvCardStatus;
    private static final int MSG_RESTART_SCAN = 4;//重新开启扫描
    private Handler mHandler;
    private TextView tv_cap;
    private String cardStateInfo;
    private PopupWindow popupWindow = null;//激活亲情卡成功
    private NetRequest netRequest;
    private RelativeLayout ll_pop_success;

    @Override
    public void onAfinalFail() {
        ToastUtils.showTextToast(ActiveFamilyActivity.this, "请检查本地网络！");
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
        mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 0);
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        //激活亲情卡成功
        if (requestId == 1) {
            //激活成功之后弹出pop
            EventBus.getDefault().post(new EventBusBean(200));
            ll_pop_success.setVisibility(View.VISIBLE);
        }//查询亲情卡状态
        else if (requestId == 2) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                String status = jsonObject.getString("status");
                //亲情卡查不到状态，说明在数据库未录入,当成未激活处理
                if (status.equals("")) {
                    //显示弹窗
                    ryScanResult.setVisibility(View.VISIBLE);
                    tvCardCode.setText(cardNo);
                    tvCardStatus.setText("未激活");
                    tvCardStatus.setTextColor(Color.parseColor("#f96116"));
                }
                //其他状态认为未激活,并吐司告诉原因
                else {
                    if (status.equals("Issue")) {
                        cardStateInfo = "该亲情卡已发卡";
                    } else if (status.equals("enable")) {
                        cardStateInfo = "该亲情卡已启用";
                    } else if (status.equals("activate")) {
                        cardStateInfo = "该亲情卡已激活";
                    } else if (status.equals("destroy")) {
                        cardStateInfo = "该亲情卡已注销";
                    } else {
                        cardStateInfo = "查询不到亲情卡状态";
                    }
                    ToastUtils.showTextToast(ActiveFamilyActivity.this, cardStateInfo);
                    mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 3000);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        //激活亲情卡失败
        if (requestId == 1) {
            ToastUtils.showTextToast(ActiveFamilyActivity.this, msg);
            mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 5000);
        }
        //查询亲情卡状态
        else if (requestId == 2) {
            ToastUtils.showTextToast(ActiveFamilyActivity.this, msg);
            mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 5000);
        }
    }

    private void initView() {
        ll_pop_success = (RelativeLayout) findViewById(R.id.ll_pop_success);
        // 设置按钮的点击事件
        ImageView occlude = (ImageView) findViewById(R.id.occlude);
        //关闭按钮
        occlude.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                ll_pop_success.setVisibility(View.GONE);
                mHandler.sendEmptyMessage(MSG_RESTART_SCAN);
            }
        });
//        TextView tvFinish = (TextView) findViewById(R.id.tv_finish);
//        //完成按钮
//        tvFinish.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ll_pop_success.setVisibility(View.GONE);
//                mHandler.sendEmptyMessage(MSG_RESTART_SCAN);
//            }
//        });
        TextView tvBinding = (TextView) findViewById(R.id.tv_binding);
        tvBinding.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_pop_success.setVisibility(View.GONE);
                mHandler.sendEmptyMessage(MSG_RESTART_SCAN);
                Intent intent = new Intent(ActiveFamilyActivity.this, BoundMemberActivity.class);
                intent.putExtra("card_no", cardNo);
                startActivity(intent);
            }
        });


        retreat = findViewById(R.id.retreat);
        ryScanResult = (RelativeLayout) findViewById(R.id.rlyt_scan_result);
        tvCardCode = (TextView) findViewById(R.id.tv_card_code);
        tvCardStatus = (TextView) findViewById(R.id.tv_card_status);

        retreat.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_cap = (TextView) findViewById(R.id.cap_tv);
        int width = LocationApplication.app.getDM().widthPixels;
        int high = LocationApplication.app.getDM().heightPixels;
        width = width / 8 * 3;
        high = high / 2 + width;
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.topMargin = high + MainActivity.dip2px(20);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        tv_cap.setLayoutParams(layoutParams);
        tv_cap.setText("扫描未发行的亲情卡上的二维码，完成激活");
    }

    private class WeakHandler extends Handler {
        private final WeakReference<ActiveFamilyActivity> mReference;

        public WeakHandler(ActiveFamilyActivity activity) {
            mReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ActiveFamilyActivity activity = mReference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case MSG_RESTART_SCAN:
                    Log.v("zyl", "重新开启扫描");
                    setReCapture();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_activefamily);
        initView();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setInintView();
        mHandler = new WeakHandler(this);
        netRequest = new NetRequest(this);
    }

    public void doCancel(View view) {
        mHandler.sendEmptyMessage(MSG_RESTART_SCAN);
        ryScanResult.setVisibility(View.GONE);
    }

    //点击取消按键
    public void doCancelActivate(View view) {
        mHandler.sendEmptyMessage(MSG_RESTART_SCAN);
        ryScanResult.setVisibility(View.GONE);
    }

    //点击激活按键
    public void doActivate(View view) {
        ryScanResult.setVisibility(View.GONE);
        netRequest.requestCardActivate(1, cardNo);
    }


    /**
     * 处理扫描结果
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();

        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(ActiveFamilyActivity.this, "扫描错误!", Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 5000);
        } else {
            if (resultString.startsWith("MTH")) {
                netRequest.requestQueryCardState(2, resultString);
                cardNo = resultString;
            } else {
                Toast.makeText(ActiveFamilyActivity.this, "此卡非亲情卡", Toast.LENGTH_SHORT).show();
                mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 5000);
            }
        }
    }
}
